package weaver.interfaces.xinri.duss.utils;

import biweekly.util.org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2023年05月18日 11:33
 */
public class InvokeHelper {
    /**汇联易测试环境*/
    // private static final String URL = "https://apistage.huilianyi.com";
    /**汇联易正式环境*/
    private static final String URL = "http://10.10.11.114";

    /**汇联易测试环境*/
    // private static final String CLIENT_ID = "f339304e-3fe4-4f4d-8745-39d8b76db35c";
    /**汇联易正式环境*/
    private static final String CLIENT_ID = "b61c89e1-5a72-40e0-b9ad-d873e8a3da67";

    /**汇联易测试环境*/
    // private static final String SECURET = "ZjE0NzMzMWUtZjVhOS00ZjVkLWE3NjAtNWNmMWVlZGY0NGQ0";
    /**汇联易正式环境*/
    private static final String SECURET = "NTBjZjI1NjUtYmNiMy00ZDdiLTkxN2QtYjM1MmMyMTI0Yjkz";

    private static final Map<String, String> STRING_MAP = new HashMap();

    static {
        STRING_MAP.put("ApprovalHistory", "/gateway/api/open/approvalHistory");
        STRING_MAP.put("Pass", "/gateway/api/open/approvals/pass");
        STRING_MAP.put("Reject", "/gateway/api/open/approvals/reject");
        STRING_MAP.put("Contract", "/gateway/api/open/contract");
        STRING_MAP.put("Change", "/gateway/api/open/contract/change");
    }

    /**
     * 获取token
     *
     * @return
     */
    private static String getAccessToken() {
        String tokenUrl = URL + "/gateway/oauth/token";
        String authStr = CLIENT_ID.concat(":").concat(SECURET);
        String authStrEnc = new String(Base64.encodeBase64(authStr.getBytes()));
        String accessToken = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout( 60, TimeUnit.SECONDS )
                    .readTimeout( 60,TimeUnit.SECONDS )
                    .writeTimeout( 60,TimeUnit.SECONDS )
                    .build();
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("grant_type", "client_credentials")
                    .addFormDataPart("scope", "write")
                    .build();
            Request request = new Request.Builder()
                    .url(tokenUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Basic ".concat(authStrEnc))
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (!"".equals(result)) {
                JSONObject resultJson = JSONObject.parseObject(result);
                accessToken = resultJson.getString("access_token");
            }
            System.out.println("response=" + result);
        } catch (Exception e) {
            System.out.println("获取token接口连接超时");
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 审批历史创建
     *
     * @param content
     * @return
     */
    public static String approvalHistory(String content) {
        return handleHttpPostRequest("ApprovalHistory", content);
    }

    /**
     * 当前审批人审批通过
     *
     * @param content
     * @return
     */
    public static String pass(String content) {
        return handleHttpPostRequest("Pass", content);
    }

    /**
     * 当前审批人审批驳回
     *
     * @param content
     * @return
     */
    public static String reject(String content) {
        return handleHttpPostRequest("Reject", content);
    }

    /**
     * 外部写入合同接口
     *
     * @param content
     * @return
     */
    public static String contract(String content) {
        return handleHttpPostRequest("Contract", content);
    }

    /**
     * 合同变更接口
     *
     * @param content
     * @return
     */
    public static String change(String content) {
        return handleHttpPostRequest("Change", content);
    }

    /**
     * http post请求处理器
     *
     * @param apiType
     * @param params
     * @return
     */
    private static String handleHttpPostRequest(String apiType, String params) {
        String result = "";
        String apiUrl = URL + Util.null2String(STRING_MAP.get(apiType));
        String accessToken = getAccessToken();
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60,TimeUnit.SECONDS)
                    .readTimeout(60,TimeUnit.SECONDS)
                    .writeTimeout(60,TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer ".concat(accessToken))
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            result = Util.null2String(response.body().string());
            if("".equals( result )){
                JSONObject resultJson = new JSONObject(  );
                resultJson.put("exception","汇联易接口返回结果为空");
                result = resultJson.toJSONString();
            }
        } catch (Exception e) {
            JSONObject resultJson = new JSONObject(  );
            resultJson.put("exception","汇联易接口响应超时");
            result = resultJson.toJSONString();
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 日期格式转换
     *
     * @param date
     * @return
     */
    public static String dateFormat(String date) {
        try {
            Date localDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            SimpleDateFormat utcSDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
            return utcSDF.format(localDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 去掉html的标签
     *
     * @param str
     * @return
     */
    public static String removeHTMLTags(String str) {
        return str.replaceAll("\\<.*?\\>", "");
    }

    public static void insertApiLog(Map<String,Object> dataMap,String apiType){
        String apiUrl = URL + Util.null2String(STRING_MAP.get(apiType));
        dataMap.put("jkqqdz",apiUrl);
        insertModelData(59,1,dataMap);
    }
    //建模权限重构
    public static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight( true );
        modeRightInfo.editModeDataShare( userid, formmodeid,id );
    }

    //将数据插入表单建模
    public static int insertModelData(int modeid, int userid, Map<String,Object> map){
        int dataid=0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery(sql,modeid);
        rs.next();
        String tablename= Util.null2String(rs.getString("tablename"));
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into "+tablename
                +"(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if(rs.executeUpdate(insSql,params)){
            rs1.executeQuery("select id from "+tablename+" where modeuuid=?",uuid);
            rs1.next();
            dataid= Util.getIntValue(rs1.getString("id"));
            if(dataid>0){
                //遍历数据 进行update
                String updatesql="update "+tablename+" set ";
                Set<String> keySet = map.keySet();
                for(String key : keySet){
                    updatesql+=key+"='"+map.get(key).toString()+"',";
                }
                if(updatesql.endsWith(",")){
                    updatesql=updatesql.substring(0, updatesql.length()-1);
                    updatesql+=" where id="+dataid;
                    rs.executeUpdate(updatesql);
                }
                //进行权限重构
                newModeRight(userid, modeid, dataid);
            }
        }
        return dataid;
    }

   public static String getWorkcodeById(String resourceid){
     RecordSet rs = new RecordSet();
     rs.executeQuery("select workcode from hrmresource where id=?",resourceid);
     rs.next();
     return Util.null2String(rs.getString(1));
   }

    public static void main(String[] args) {
       String htje = "79000.09";
        System.out.println(Util.getDoubleValue(htje)>0);
    }

}
